import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'common/channel/extremely_rich_channel.dart';
import 'common/observer/visibilityObserver.dart';
import 'common/router/router_map.dart';
import 'common/third/boost/MyFlutterBinding.dart';
import 'common/third/boost/interceptor/YZBoostInterceptor.dart';
import 'common/widgets/CommonWidget.dart';

void main() {
  /// 生命周期监听
  PageVisibilityBinding.instance.addGlobalObserver(AppGlobalPageVisibilityObserver());

  ///这里的CustomFlutterBinding调用务必不可缺少，用于控制Boost状态的resume和pause
  MyFlutterBinding();

  ///监听原生app配置
  ///使用boost的监听，在flutter侧的main函数里，会报
  ///'_appState != null': Please check if the engine has been initialized!
  ///采用系统channel
  ExtremelyRichChannel.instance.listenToNativeConfig();

  //异常日志分析
  FlutterError.onError = (details) async {
    if (kDebugMode) {
      // In development mode simply print to console
      FlutterError.dumpErrorToConsole(details);
    } else {
      //转发到Zone中
      // In production mode report to the application zone
      Zone.current.handleUncaughtError(details.exception,
          details.stack ?? StackTrace.fromString("no stackTraceString"));
    }
  };
  runZonedGuarded(() {
    runApp(const YouthApp());
  }, ((error, stack) {
    //Do sth for error
    String message =
        "error = ${error.toString()} \n stackTrace ${stack.toString()}";
    debugPrint(message);
    //TODO: 通过channel调用native方法，把error栈的信息传的native中，
    //native端接收到error栈信息后上报fabric crashlytics

    //reportError
  }));
}

// flutter_boost
class YouthApp extends StatelessWidget {
  const YouthApp({super.key});

  Route<dynamic>? routeFactory(RouteSettings settings, String? uniqueId) {
    debugPrint("settings.name ${settings.name}");
    FlutterBoostRouteFactory? func = YouthRoute.routerMap[settings.name];
    // FlutterSmartDialog监听
    return FlutterSmartDialog.boostMonitor(func?.call(settings, uniqueId));
  }

  @override
  Widget build(BuildContext context) {
    //SmartDialog初始化代码必须放在FlutterBoostApp之前
    var initSmartDialog = FlutterSmartDialog.init(
      toastBuilder: (msg) => CustomToast(msg),
    );

    return FlutterBoostApp(
      routeFactory,
      appBuilder: (Widget home) {
        //FlutterSmartDialog监听
        return MaterialApp(
          home: home,
          debugShowCheckedModeBanner: false,

          ///必须加上builder参数，否则showDialog等会出问题
          builder: (context, child) {
            return initSmartDialog(context, home);
          },
        );
      },
      interceptors: [YZBoostInterceptor()],
    );
  }
}